/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package stock.utils.html;

import java.net.URL;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author peter
 */
public class SinaCrawler {

    private final String TARGET = "http://hq.sinajs.cn/list=";

    public String getStockState(String code) throws Exception {
        String stock = format(code);
        URL url = new URL(TARGET+stock);
        Scanner in = new Scanner(url.openStream(), "gbk");
        StringBuilder sb = new StringBuilder();
        while (in.hasNextLine()) {
            sb.append(in.nextLine());
        }
        in.close();
        return sb.toString();
    }

    public String getPrice(String code) {
        try {
            String state = getStockState(code);
            String[] split = state.split(",");
            if (split.length > 3) {
                return split[3].trim();
            }
        } catch (Exception ex) {
            Logger.getLogger(SinaCrawler.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    private String format(String code) {
        if (code.startsWith("6"))
            return "sh"+code;
        return "sz"+code;
    }

    public static void main(String[] args) throws Exception {

        SinaCrawler sina = new SinaCrawler();
        System.out.println("code: "+sina.getPrice("600588"));
        System.out.println("code: "+sina.getStockState("600588"));
    }

}
